package com.paipai.listen;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.paipai.entity.Product;
import com.paipai.service.productService;
import com.rabbitmq.client.Channel;

@Component
public class RabbitListen {

	@Autowired
	private productService productService;
	
	
	@Autowired
	private StringRedisTemplate srtle;

	@RabbitHandler
	@RabbitListener(bindings = @QueueBinding(value = @Queue(
			value = "paipai.productState.queue", durable = "true"), 
			exchange = @Exchange(value = "paipai.productState.exchange", ignoreDeclarationExceptions = "true"), 
			key = "paipai.state.product"))
	public void ProductState(Message message, @Headers Map<String, Object> headers, Channel channel)
			throws IOException {
			System.out.println("product接受到消息");
			
			// 获得消息的id 通过uuid生成
			String messageId = message.getMessageProperties().getMessageId();
			
			//防重复提交 幂等性  
			BoundValueOperations<String, String> bouoprations = srtle.boundValueOps(messageId);
			String value = bouoprations.get();
			//如果euqls等于A,证明该消息已经被消费过了
			if(value!=null) {
				// 拒绝消息                                   true表示 重新打回队列,   false表示 丢弃消息
				channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
				System.out.println("反重复生效");
				return;
			}
			

			// 获取消息的主体内容
			String msgBody = new String(message.getBody(), "UTF-8");
			@SuppressWarnings("unchecked")
			HashMap<String, Object> map = JSON.parseObject(msgBody, HashMap.class);

			int row = productService.updateProductStatus(map);
			
			if (row > 0) {
				// 手动签收消息,通知mq服务器端删除该消息 false表示不批量处理
				System.out.println("签收");
				//消费成功 往redis 放入值
				bouoprations.set("A");
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

			}

		
	}

}
